require(['./config'], () => {
    require(['login-reg', 'server', 'template', 'nav', 'foot', 'zoom', 'fly'], (loginreg, server, template, nav) => {
        class Category {
            constructor() {
                this.init().then(() => {
                    $('.goods_cart').on('click', (e) => {
                        this.addCart(e)
                    })
                    this.zoom()
                })
            }
            init() {
                const goodid = window.location.hash.split("=");

                return new Promise(resolve => {
                    $.get(server.baseServerUrl + '/api/v1/goods/select.php', resp => {
                        // let resp = $.respGoods;
                        let res = JSON.parse(resp).body.list[goodid[1] - 1]
                        $('.goodcrumb').append(`<i>&gt;</i> <a href="${window.location.href}">${res.name}</a>`);

                        res.desc = res.desc.split('&')
                        res.img = res.img.split('@');
                        res.size = res.size.split('@');

                        res.elseSpecs ? res.elseSpecs = res.elseSpecs.split('@') : res.elseSpecs = false;
                        res.choose ? res.choose = res.choose.split('&') : res.choose = false;
                        const str = template('goods-one-detail', {...res })
                        this.detail = res
                        $('.goods_desc').html(str)
                        resolve();
                    })
                })

            }
            noLoginAdd(e) {
                this.fly(e)
                let cart = localStorage.getItem('cart')
                let car_size = $('.spec_list').val()

                if (cart) {
                    cart = JSON.parse(cart);
                    this.detail.id = window.location.hash.split("=")[1]
                    console.log(this.detail.id);
                    const isExist = cart.some(shop => shop.goodid === this.detail.id)
                    if (isExist) {
                        // 当前商品在购物车里以存在
                        // 根据id找到这件商品，然后count++
                        cart = cart.map(shop => {
                            if (shop.goodid === this.detail.id) shop.count++
                                return shop
                        })
                    } else {
                        // 当前商品还没有被加入过购物车
                        cart.push({
                            ...this.detail,
                            count: 1,
                            car_size: car_size,
                            check: true
                        })
                    }
                    localStorage.setItem('cart', JSON.stringify(cart))
                } else {
                    localStorage.setItem('cart', JSON.stringify([{
                        ...this.detail,
                        // car_size:
                        count: 1,
                        car_size: car_size,
                        check: true
                    }]))

                }
            }
            addCart(e) {
                let goodid = window.location.hash.split("=");
                let goods_id = goodid[1];
                let phone = $.userphone;
                let car_size = $('.spec_list').val()

                if (!phone) {
                    this.noLoginAdd(e);
                    return
                }

                this.fly(e);
                let shopcar_list = [];
                $.post(server.baseServerUrl + '/api/v1/goods/selectCart.php', { phone }, resp => {
                    if (JSON.parse(resp).code == 200) {

                        shopcar_list = JSON.parse(resp).body.list

                        let alredyCart = shopcar_list.filter((item) => {
                            return item.goods_id == goods_id
                        })

                        let goods_count = 1;

                        if (alredyCart.length) {
                            goods_count = (parseInt(alredyCart[0].goods_count)) + 1;
                            $.post(server.baseServerUrl + '/api/v1/goods/updateCarCount.php', { goods_id, phone, goods_count, car_size }, resp => {
                                loginreg.queryCart(phone);
                            })
                            return
                        }

                        $.post(server.baseServerUrl + '/api/v1/goods/addCart.php', { goods_id, phone, goods_count, car_size }, resp => {
                            loginreg.queryCart(phone);
                        })
                    }
                })

            }
            fly(e) {
                $(`<img src="${this.detail.img[0]}" style="width: 10px;height: 10px;border-radius:50% ;background-color:red;z-index=100">`).fly({
                    start: {
                        left: e.clientX, //开始位置（必填）#fly元素会被设置成position: fixed
                        top: e.clientY, //开始位置（必填）
                    },
                    end: {
                        left: $(window)[0].innerWidth, //结束位置（必填）
                        top: 0 //结束位置（必填）
                    },
                    speed: 0.8, //越大越快，默认1.2
                    vertex_Rtop: 0, //运动轨迹最高点top值，默认20
                    onEnd: function() {
                            this.destroy()
                            nav.calcCartCount()
                        } //结束回调
                })
            }
            zoom() {
                // 在小图的a标签上制定data-image是对应中图的src，data-zoom-image对应大图的src
                // gallery参数是小图容器的id（不加#）
                $('.zoom-image').elevateZoom({
                    gallery: 'gal1'
                })
            }
        }
        new Category()
    })
})